//$Id: management.js,v 1.9 2008/10/18 18:25:04 silviogutierrez Exp $

var GallerixManager = GallerixManager || {};


$(document).ready(function() {

  //Start up the manager.
  GallerixManager.init();
  
});



/**
 * Sets the cursor, binds the keys, and initializes globals.
 *
 */
GallerixManager.init = function() {
  
  //Load settings.
  GallerixManager.index = Drupal.settings.gallerixManager.index; 
  GallerixManager.pictures = Drupal.settings.gallerixManager.pictures;
  GallerixManager.captions = Drupal.settings.gallerixManager.captions;  
  GallerixManager.settings = Drupal.settings.gallerixManager.settings;

  
  GallerixManager.current = 0;
  GallerixManager.count = Drupal.settings.gallerixManager.count;  
  
  GallerixManager.initKeys();
  
  //Initialize tabbing functionality.
  $('.gallerix-caption-field').focus(function () {
    
    GallerixManager.focus(GallerixManager.getID(this.id));
  });
  
  
  //Initialize thumbnail clicking functionality.
  $('.gallerix-thumbnail-field').click(function () {
  
    $('#gallerix-caption-field-' + GallerixManager.getID(this.id)).get(0).focus();
  
  });
  
  //Create a delete object.
  GallerixManager.toDelete = {};
  
  
  //Initialize deletion functionality.
  $('.gallerix-delete-field').click(function () {
    
    var pid = GallerixManager.getID(this.id);
    GallerixManager.flagDeletion(pid);
    
    //Switch the buttons.
    $(this).hide();
    $('#gallerix-restore-field-' + pid).show();
    
    return false;
  });
  
  
  //Initialize restore functionality.
  $('.gallerix-restore-field').click(function () {
    
    var pid = GallerixManager.getID(this.id);
    GallerixManager.unflagDeletion(pid);
    
    //Switch the buttons.
    $(this).hide();
    $('#gallerix-delete-field-' + pid).show();
    
    return false;
  }); 
  
  
  GallerixManager._initSort();
  GallerixManager._initCaptions();
  
  
  //Enable save button.
  $('.gallerix-management-save').click(function () {
    GallerixManager.save();
    return false;
  });
  
  
  var first = GallerixManager.index[0];
  
  
  //Focus on the first field.
  $('#gallerix-caption-field-' + first).get(0).focus();
  
  GallerixManager.current = 0;
  
  
}





/** 
 * Initializes sorting links.
 *
 */
GallerixManager._initSort = function () {
  $('.gallerix-up-field').click(function () {
    GallerixManager.moveUp(GallerixManager.getID(this.id));
    return false;  
  });
  
  $('.gallerix-down-field').click(function () {
    GallerixManager.moveDown(GallerixManager.getID(this.id));
    return false;   
  });

  $('.gallerix-top-field').click(function () {
    GallerixManager.moveTop(GallerixManager.getID(this.id));
    return false;   
  });

  
  $('.gallerix-bottom-field').click(function () {
    GallerixManager.moveBottom(GallerixManager.getID(this.id));
    return false;   
  });
}


/**
 * Populate the caption fields.
 *
 */
GallerixManager._initCaptions = function () {
  $('.gallerix-caption-field').each(function () {
  
    var pid = GallerixManager.getID(this.id);
    
    $('#gallerix-caption-field-' + pid).val(GallerixManager.captions[pid]);
  });


}



/************************** Key Shortcuts *****************************/



/**
 * Bind special keys to their new functions.
 *
 */
GallerixManager.initKeys = function () {

  $(document).keydown(function(key) {
    var pid = GallerixManager.index[GallerixManager.current];
  
    if (key.keyCode) {
      
      
      switch(key.keyCode) {
        case 9: { // Tab
          return GallerixManager.tab(key.shiftKey);   
        }
        case 38: { // Up
          if (key.ctrlKey && GallerixManager.settings.allowSorting) {
            GallerixManager.moveUp(pid);
            GallerixManager.focus(pid);
            return false;
          }        
        }       
        case 40: { // Down
          if (key.ctrlKey && GallerixManager.settings.allowSorting) {
            GallerixManager.moveDown(pid);
            GallerixManager.focus(pid);
            return false;
          }
        }
        case 83: { // Letter S
          if (key.ctrlKey && GallerixManager.settings.allowSorting) {
            GallerixManager.save();
            return false;
          }        
        
        }

      
      }
      
    }
    else if(key.charCode) {
    
    
    
    }
    else {
      
    }
    
    return true;
    

  });
}



/**
 * Switches to the next available picture.
 *
 */
GallerixManager.tab = function (shift) {
  
  if (GallerixManager.count == 0) {
    return false;
  }
  
  
  var newIndex = shift ? GallerixManager.current - 1 : GallerixManager.current + 1;
  
  if (newIndex == GallerixManager.index.length) {
    newIndex = 0;
  }
  else if (newIndex == -1) {
    newIndex = GallerixManager.index.length - 1;
  }  

  var target = GallerixManager.index[newIndex];

  $('#gallerix-caption-field-' + target).get(0).focus();
  
  return false;
}





/****************************** Save **********************************/


/**
 * Save all the changes with an AJAX request.
 *
 */
GallerixManager.save = function () {


  //Delete pictures we don't need to process.
  GallerixManager.deletePictures();
  
  
  //Prepare a JSON containing all the data to save.
  var data = {};
 


  for (var pid in GallerixManager.toDelete) {
    data[pid] = 'delete' + '|#|';   
  }
  
  
  
  
  
  for (var pid in GallerixManager.pictures) {

    var index = GallerixManager.pictures[pid];
    var caption = $('#gallerix-caption-field-' + pid).val();    
    
    data[pid] = "sort" + "|#|" + index + "|#|" + caption; 
  }
  

  $.post(GallerixManager.settings.submitURL, data, function (data) {
  
    var result = Gallerix.parseJson(data);
    
    switch (result.status) {
      case 'error': {
        Gallerix.setError(result.message, 5000);
        break;
      }
      case 'success': {
        Gallerix.setStatus(result.message, 5000);
        break;
      }
      case 'reload': {
        Gallerix.setStatus(result.message);
        window.location = GallerixManager.settings.reloadURL;
        break;
      }
    
    
    }
    
    
    
    
    
    GallerixManager.deleteRows();
    GallerixManager.rebuildTable();
    
    //Clear the delete object.
    GallerixManager.toDelete = {};
    
  }); 
  
}




/***************************** Focus **********************************/


/**
 * Indicate which picture is selected.
 *
 */
GallerixManager.focus = function (current) {
  var index = GallerixManager.pictures[current];
   
  GallerixManager.current = parseInt(index);

  $('.gallerix-thumbnail-field').css({border: 'none', margin: '2px'});
  $('#gallerix-thumbnail-field-' + current).css({border: '2px solid black', margin: '0'});

}






/**************************** Actions *********************************/


/**
 * Moves the row one slot up, unless the row is already at the very top.
 *
 */
GallerixManager.moveUp = function (pid) {
  var index = GallerixManager.pictures[pid];
  
  
  //Check to see if we're at the top.
  if (index == 0) {
    Gallerix.setError('Image already on top.');
    return;
  }
  

  GallerixManager.switchRows(index, index - 1);

}


/**
 * Moves the row one slot down, unless the row is already at the very bottom.
 *
 */
GallerixManager.moveDown = function (pid) {
  var index = GallerixManager.pictures[pid];
  var length = GallerixManager.index.length;
  
  //Check to see if we're at the bottom.
  if (index == length - 1) {
    Gallerix.setError('Image already at the bottom.');
    return;
  }
  

  GallerixManager.switchRows(index, index + 1);

}


/**
 * Moves the row to the very top, unless the row is already at the top.
 *
 */
GallerixManager.moveTop = function (pid) {
  var index = GallerixManager.pictures[pid];

  //Check to see if we're at the top.
  if (index == 0) {
    Gallerix.setError('Image already on top.');
    return;
  }
  

  GallerixManager.shiftTop(index);

}




/**
 * Moves the row to the very bottom, unless the row is already at the bottom.
 *
 */
GallerixManager.moveBottom = function (pid) {
  var index = GallerixManager.pictures[pid];
  
  //Check to see if we're at the bottom.
  if (index == GallerixManager.count - 1) {
    Gallerix.setError('Image already at the bottom.');
    return;
  }
  

  GallerixManager.shiftBottom(index);

}


/*************************** Deletion *********************************/


/**
 * Queues up the picture for deletion.
 *
 */
GallerixManager.flagDeletion = function (pid) {
  GallerixManager.toDelete[pid] = true;
  
  //Clearly mark the row to be deleted.
  $('#gallerix-management-row-' + pid).css('background-color', '#FFCCCC'); 

}


/**
 * Remove a picture from the delete queue.
 *
 */
GallerixManager.unflagDeletion = function (pid) {
  delete GallerixManager.toDelete[pid];
  
  //Clearly mark the row to be deleted.
  $('#gallerix-management-row-' + pid).css('background-color', ''); 

}


/**
 * Go through the deletion array and remove each pid from the main index.
 *
 */
GallerixManager.deletePictures = function () {
  for (var pid in GallerixManager.toDelete) {
    GallerixManager.rebuildIndex(pid);
    GallerixManager.count--;
  }
}



/**
 * Delete rows which contain pictures that were deleted.
 *
 */
GallerixManager.deleteRows = function () {
  for (var pid in GallerixManager.toDelete) {
    $('#gallerix-management-row-' + pid).remove();
  }

}

 


/**
 * Rebuilds the index by realigning all the pictures with the indices.
 *
 * @param pid is the picture that should be left out.
 */
GallerixManager.rebuildIndex = function (pid) {

  var index = GallerixManager.pictures[pid];
  var length = GallerixManager.index.length;
  
  for (var x = index; x < length - 1; x++) {

    GallerixManager.index[x] = GallerixManager.index[x + 1];
    GallerixManager.pictures[GallerixManager.index[x]] = x;
  }
  
  GallerixManager.index = GallerixManager.index.slice(0, length - 1);
  delete GallerixManager.pictures[pid];
  
}



/**************************** Utilities *******************************/


/**
 * Get the ID of a picture using it's CSS id.
 *
 */
GallerixManager.getID = function (css) {
  var index = css.lastIndexOf('-');

  return css.substring(index + 1); 
}




/**
 * Rebuild table zebra stripes.
 *
 */
GallerixManager.rebuildTable = function () {
  var counter = 1;
  
  $('.gallerix-management-row').each(function () {
    $(this).removeClass('odd').removeClass('even');
    
    if (counter % 2) {
      $(this).addClass('odd');
    }
    else {
      $(this).addClass('even');
    }
    
    counter++;
  });


}




/**
 * Switch two rows in the table. No validity checks performed.
 * 
 */
GallerixManager.switchRows = function (source, destination) {
  
  var sourcePID = GallerixManager.index[source];
  var destPID = GallerixManager.index[destination];
  
  //Switch the picture with the picture in the destination index.  
  GallerixManager.pictures[destPID] = source;
  GallerixManager.pictures[sourcePID] = destination;
  
  GallerixManager.index[source] = destPID;
  GallerixManager.index[destination] = sourcePID;
  
  
  var sourceRow = $('#gallerix-management-row-' + sourcePID);
  var destRow = $('#gallerix-management-row-' + destPID);
  
  //Switch the actual DOM elements.
  if (destination > source) {
    $(sourceRow).insertAfter(destRow);  
  }
  else {
    $(sourceRow).insertBefore(destRow);
  }
    

  
  //Switch the coloring.
  $(sourceRow).toggleClass('odd').toggleClass('even');
  $(destRow).toggleClass('odd').toggleClass('even');  

  //Restripe.
  GallerixManager.rebuildTable();

}


/**
 * Switch a row to the very top.
 * 
 */
GallerixManager.shiftTop = function (source, destination) {
  
  var sourcePID = GallerixManager.index[source];
  var destPID = GallerixManager.index[0];
  
  var tempArray = new Array();
  
  GallerixManager.rebuildIndex(sourcePID);

  for (var x in GallerixManager.index) {
    var index = parseInt(x);
    
    GallerixManager.pictures[GallerixManager.index[index]] = index + 1; 
    tempArray[index + 1] = GallerixManager.index[x];
  }
  
  tempArray[0] = sourcePID;
  GallerixManager.pictures[sourcePID] = 0;
  GallerixManager.index = tempArray;
  
  var sourceRow = $('#gallerix-management-row-' + sourcePID);
  var destRow = $('#gallerix-management-row-' + destPID);
  
  
  //Switch the actual DOM elements.
  $(sourceRow).insertBefore(destRow);

    
  //Restripe.
  GallerixManager.rebuildTable();

}


/**
 * Switch a row to the very bottom.
 * 
 */
GallerixManager.shiftBottom = function (source) {
  
  var sourcePID = GallerixManager.index[source];
  var destPID = GallerixManager.index[GallerixManager.count - 1];
  
  GallerixManager.rebuildIndex(sourcePID);
  
  GallerixManager.pictures[sourcePID] = GallerixManager.count - 1;
  GallerixManager.index[GallerixManager.count - 1] = sourcePID;
  

  var sourceRow = $('#gallerix-management-row-' + sourcePID);
  var destRow = $('#gallerix-management-row-' + destPID);
  
  //Switch the actual DOM elements.
  $(sourceRow).insertAfter(destRow);

    
  //Restripe.
  GallerixManager.rebuildTable();
}






